package com.dlwx.parttimetalent.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.base.BaseActivity;
import com.dlwx.parttimetalent.bean.BaseBean;
import com.dlwx.parttimetalent.bean.UserBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.inter.DialogTwoBtnInter;
import com.dlwx.parttimetalent.utils.CheckUtil;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.DialogUtils;
import com.dlwx.parttimetalent.utils.HxUtils;
import com.dlwx.parttimetalent.utils.LogUtils;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.dlwx.parttimetalent.utils.TimeCount;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.dlwx.parttimetalent.wechatpay.wxapi.WxLoginutiles;
import com.dlwx.parttimetalent.weibo.WeiboUitls;
import com.dlwx.parttimetalent.wxapi.CallBackListenerUtiles;
import com.dlwx.parttimetalent.wxapi.QQUtiles;
import com.flyco.dialog.widget.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.tauth.Tencent;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;


public class LoginActivity extends BaseActivity {
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.view_line_login)
    View viewLineLogin;
    @BindView(R.id.rel_login_group)
    RelativeLayout relLoginGroup;
    @BindView(R.id.view_line_register)
    View viewLineRegister;
    @BindView(R.id.rel_register_group)
    RelativeLayout relRegisterGroup;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.image_name)
    ImageView imageName;
    @BindView(R.id.image_psw)
    ImageView imagePsw;
    @BindView(R.id.et_psw)
    EditText etPsw;
    @BindView(R.id.tv_find_psw)
    TextView tvFindPsw;
    @BindView(R.id.tv_three_login)
    TextView tvThreeLogin;
    @BindView(R.id.image_wechat)
    ImageView imageWechat;
    @BindView(R.id.image_qq)
    ImageView imageQq;
    @BindView(R.id.image_weibo)
    ImageView imageWeibo;
    @BindView(R.id.image_phone)
    ImageView imagePhone;
    @BindView(R.id.et_reg_phone)
    EditText etRegPhone;
    @BindView(R.id.image_yzm)
    ImageView imageYzm;
    @BindView(R.id.et_yzm)
    EditText etYzm;
    @BindView(R.id.tv_get_yzm)
    TextView tvGetYzm;
    @BindView(R.id.ll_name)
    LinearLayout llName;
    @BindView(R.id.et_reg_psw)
    EditText etRegPsw;
    @BindView(R.id.img_eye)
    ImageView imgEye;
    @BindView(R.id.rl_psw)
    RelativeLayout rlPsw;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    @BindView(R.id.tv_ret_agreement)
    TextView tvRetAgreement;

    ViewGroup layoutLogin;
    ViewGroup layoutRegister;
    @BindView(R.id.tv_choose_login)
    TextView tvChooseLogin;
    @BindView(R.id.tv_choose_reg)
    TextView tvChooseReg;
    @BindView(R.id.img_login_eye)
    ImageView imgLoginEye;
    private TimeCount timeCount = null;
    private String name;
    private String psw;
    private String regPhone;
    private String regPsw;
    private String yzm;
    private boolean isSee = false;
    private boolean isLoginSee = false;
    private RxPermissions rxpermissions;
    private String apiToken;
    private int clientId;
    private SsoHandler mSsoHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_login1);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        apiToken = (String) SPUtils.get(this, Constant.API_TOKEN, "");
        clientId = (int) SPUtils.get(this, Constant.CLIENT_ID, -1);
        layoutLogin = findViewById(R.id.layout_login);
        layoutRegister = findViewById(R.id.layout_register);
        CallBackListenerUtiles.setCallBackListener(callBackListener);
    }

    private CallBackListenerUtiles.ShareCallBackListener callBackListener = new CallBackListenerUtiles.ShareCallBackListener() {
        @Override
        public void setComplete() {

        }

        @Override
        public void getUserInfo(String nickName, String imagePic, String openID, String gender, String lg_status) {
            loginUser("", "", lg_status, imagePic, nickName, openID);
        }
    };

    @OnClick({R.id.tv_find_psw, R.id.image_wechat, R.id.image_qq
            , R.id.image_weibo, R.id.tv_get_yzm, R.id.tv_login
            , R.id.img_eye, R.id.tv_register, R.id.tv_ret_agreement
            , R.id.rel_login_group, R.id.rel_register_group, R.id.tv_agreement,R.id.img_login_eye})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
//                startActivity(new Intent(this,DaRenActivity.class));
                checkLoginInfo();
                break;
            case R.id.tv_find_psw:
                startActivity(new Intent(LoginActivity.this, FindPswActivity.class));
                break;
            case R.id.image_wechat:
                loadingDialog.show();
                WxLoginutiles wxLogin = new WxLoginutiles(this);
                wxLogin.loginWx(this);
                break;
            case R.id.image_qq:
                loadingDialog.show();
                QQUtiles qqUtiles = new QQUtiles();
                qqUtiles.LoginQQ(this);
                break;
            case R.id.image_weibo:
                loadingDialog.show();
                WeiboUitls util = new WeiboUitls(this);
                mSsoHandler = util.getSso();
                util.login();
                break;
            case R.id.tv_get_yzm:
                regPhone = etRegPhone.getText().toString();
                if (TextUtils.isEmpty(regPhone) || !CheckUtil.isMobileNO(regPhone)) {
                    ToastUtils.toastForShort(this, "请输入正确手机号码");
                    return;
                }
                getYzm(regPhone);
                break;
            case R.id.img_eye:
                if (isSee) {
                    etRegPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    isSee = false;
                    imgEye.setImageResource(R.mipmap.icon_yanjinga);
                } else {
                    etRegPsw.setInputType(InputType.TYPE_CLASS_TEXT);
                    isSee = true;
                    imgEye.setImageResource(R.mipmap.icon_yanjingb);
                }
                break;
            case R.id.tv_register:
//                startActivity(new Intent(this,ChooseSexActivity.class));
                checkRegInfo();
                break;
            case R.id.tv_ret_agreement:
                startActivity(new Intent(this, AgreementActivity.class));
                break;
            case R.id.tv_agreement:
                startActivity(new Intent(this, AgreementActivity.class));
//                startActivity(new Intent(this,AgreementActivity.class));
                break;
            case R.id.rel_login_group:
                showLoginOrReg(0);
                break;
            case R.id.rel_register_group:
                showLoginOrReg(1);
                break;
            case R.id.img_login_eye:
                if (isLoginSee) {
                    etPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    isLoginSee = false;
                    imgLoginEye.setImageResource(R.mipmap.icon_yanjinga);
                } else {
                    etPsw.setInputType(InputType.TYPE_CLASS_TEXT);
                    isLoginSee = true;
                    imgLoginEye.setImageResource(R.mipmap.icon_yanjingb);
                }
                break;
        }
    }

    private void showLoginOrReg(int i) {
        if (i == 0) {
            layoutLogin.setVisibility(View.VISIBLE);
            layoutRegister.setVisibility(View.GONE);
            tvChooseLogin.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
            tvChooseReg.setTextColor(ContextCompat.getColor(this, R.color.first_textcolor));
            viewLineRegister.setBackgroundColor(ContextCompat.getColor(this, R.color.bg));
            viewLineLogin.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
        } else {
            layoutLogin.setVisibility(View.GONE);
            layoutRegister.setVisibility(View.VISIBLE);
            tvChooseLogin.setTextColor(ContextCompat.getColor(this, R.color.first_textcolor));
            tvChooseReg.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
            viewLineLogin.setBackgroundColor(ContextCompat.getColor(this, R.color.bg));
            viewLineRegister.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
        }

    }

    private void getYzm(String phone) {
        OkGo.<String>post(Http.YZM)
                .params("apitoken", apiToken)
                .params("clientid", clientId)
                .params("phone_no", phone)
                .params("status", 1)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response == null) {
                            return;
                        }
                        String res = response.body().toString();
                        BaseBean bean = new Gson().fromJson(res, BaseBean.class);
                        if (bean == null) {
                            return;
                        }
                        ;
                        if (bean.getCode() == Constant.SUCESS) {
                            timeCount = new TimeCount(tvGetYzm, 2 * 60 * 1000, 1000, "#ffffff");
                            timeCount.start();
                        }
                        ToastUtils.toastForShort(LoginActivity.this, bean.getResult());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(LoginActivity.this, getString(R.string.bad_net));
                    }
                });

    }

    private void checkRegInfo() {
        regPhone = etRegPhone.getText().toString();
        regPsw = etRegPsw.getText().toString();
        yzm = etYzm.getText().toString();
        if (TextUtils.isEmpty(regPhone) || !CheckUtil.isMobileNO(regPhone)) {
            ToastUtils.toastForShort(this, "请输入正确手机号码");
            return;
        }
        if (TextUtils.isEmpty(yzm)) {
            ToastUtils.toastForShort(this, "验证码不能为空");
            return;
        }
        if (TextUtils.isEmpty(regPsw) || !CheckUtil.checkPassword(regPsw)) {
            ToastUtils.toastForShort(this, "用户密码6-18位数字和字母组合");
            return;
        }
        MaterialDialog dialog = DialogUtils.getMaterialDialogTwoBtn(this, "请确认当前手机号：", regPhone, new DialogTwoBtnInter() {
            @Override
            public void confirm() {
                registerUser(regPhone, regPsw, yzm);
            }

            @Override
            public void cancel() {
            }
        });
        dialog.show();

    }

    private void registerUser(final String regPhone, final String regPsw, String yzm) {
        OkGo.<String>post(Http.REGISTER)
                .params("apitoken", apiToken)
                .params("clientid", clientId)

                .params("phone_no", regPhone)
                .params("password", regPsw)
                .params("repassword", regPsw)
                .params("codeno", yzm)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response == null) {
                            return;
                        }
                        String res = response.body().toString();
                        BaseBean bean = new Gson().fromJson(res, BaseBean.class);
                        if (bean == null) {
                            return;
                        }
                        ;
                        if (bean.getCode() == Constant.SUCESS) {
                            etRegPhone.setText("");
                            etRegPsw.setText("");
                            etYzm.setText("");
                            etName.setText(regPhone);
                            etPsw.setText(regPsw);
                            showLoginOrReg(0);
                        }
                        ToastUtils.toastForShort(LoginActivity.this, bean.getResult());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(LoginActivity.this, getString(R.string.bad_net));
                    }
                });
    }

    private void checkLoginInfo() {
        name = etName.getText().toString();
        psw = etPsw.getText().toString();
        if (TextUtils.isEmpty(name) || !CheckUtil.isMobileNO(name)) {
            ToastUtils.toastForShort(this, "请输入正确手机号码");
            return;
        }
        if (TextUtils.isEmpty(psw) || !CheckUtil.checkPassword(psw)) {
            LogUtils.d(CheckUtil.checkPassword(psw) + "--" + psw);
            ToastUtils.toastForShort(this, "用户密码6-18位数字和字母组合");
            return;
        }

        loginUser(name, psw, "1", "", "", "");
//        startActivity(new Intent(LoginActivity.this, LoginActivity.class));
    }

    private void loginUser(String name, String psw, final String type, final String headurl, final String nickname, final String third_no) {
        loadingDialog.show();
        OkgoUtil.post(Http.LOGIN, this)
                .params("phone_no", name)
                .params("password", psw)
                .params("lg_status", type)
                .params("headurl", headurl)
                .params("nickname", nickname)
                .params("third_no", third_no)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        UserBean userBean = DealResult.getInstance().dealDatas(LoginActivity.this, response, new TypeToken<UserBean>() {
                        }.getType());
                        if (userBean == null) {
                            return;
                        }
                        int code = userBean.getCode();
                        if (code == Constant.THIRD) {
                            Intent i = new Intent(LoginActivity.this, BindPhoneActivity.class);
                            i.putExtra("third_no", third_no);
                            i.putExtra("lg_status", type);
                            i.putExtra("headurl", headurl);
                            i.putExtra("nickname", nickname);
                            startActivity(i);
                        } else if (userBean.getCode() == Constant.SUCESS) {
                            UserBean.BodyBean bean = userBean.getBody();
                            HxUtils.login(bean.getUserid() + "");
                            Set<String> tags = new HashSet<>();
                            tags.add(bean.getUserid() + "");
                            JPushInterface.setTags(getApplicationContext(), 1, tags);
                            SPUtils.put(LoginActivity.this, Constant.USER_ID, bean.getUserid());
                            SPUtils.put(LoginActivity.this, Constant.USER_Token, bean.getUser_token());
                            SPUtils.put(LoginActivity.this, Constant.OPEN_ID, third_no);
                            SPUtils.put(LoginActivity.this, Constant.HEAD_URL, bean.getHeadurl());
                            SPUtils.put(LoginActivity.this, Constant.NICK_NAME, bean.getNickname());
                            SPUtils.put(LoginActivity.this, Constant.ZONDIAC, bean.getZodiac());
                            SPUtils.put(LoginActivity.this, Constant.PHONE, bean.getPhone_no());
                            if (bean.getPassword() == 2) {
                                LoginActivity.this.finish();
                                Intent i = new Intent(LoginActivity.this, SetPswActivity.class);
                                i.putExtra("flag", 0);
                                startActivity(i);
                            } else if (bean.getSetsex() == 2) {
                                LoginActivity.this.finish();
                                startActivity(new Intent(LoginActivity.this, ChooseSexActivity.class));
                            } else if (bean.getIntent() == 2) {
                                LoginActivity.this.finish();
                                startActivity(new Intent(LoginActivity.this, SetLabel1211Activity.class));
                            } else {
                                toMain(bean);
                            }
                        } else {
                            ToastUtils.toastForShort(LoginActivity.this, userBean.getResult());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                        ToastUtils.toastForShort(LoginActivity.this, getString(R.string.bad_net));
                    }
                });
    }

    private void toMain(UserBean.BodyBean bean) {
        SPUtils.put(LoginActivity.this, Constant.isLogin, true);
        if (1 == bean.getSex()) {
            SPUtils.put(LoginActivity.this, Constant.SEX, "男");
        } else {
            SPUtils.put(LoginActivity.this, Constant.SEX, "女");
        }
        LoginActivity.this.finish();
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeCount != null) {
            timeCount.cancel();
            timeCount = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, new QQUtiles().uiListener);
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
}
